<template>
  <div id="goTop">
    <div class="goTop" v-show="goTopShow" @click="goTop"><van-icon name="upgrade" class="go-top"/></div>
  </div>
</template>
<script>
export default {
  name: 'goTop',
  data () {
    return {
      scrollTop: 0,
      goTopShow: false
    }
  },
  methods: {
    handleScroll () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      // 如果滚动距离大于50则显示返回顶部
      if (this.scrollTop > 50) {
        this.goTopShow = true
      } else {
        this.goTopShow = false
      }
    },
    goTop () {
      let timer = null
      let _that = this
      cancelAnimationFrame(timer)
      timer = requestAnimationFrame(function fn () {
        if (_that.scrollTop > 0) {
          _that.scrollTop -= 15
          document.body.scrollTop = document.documentElement.scrollTop = _that.scrollTop
          timer = requestAnimationFrame(fn)
        } else {
          cancelAnimationFrame(timer)
          _that.goTopShow = false
        }
      })
    }
  },
  mounted () {
    // 监听滚动事件处理
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed () {
    // 移除滚动事件
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>
<style scoped>
  .goTop{
    position: fixed;
    z-index: 100;
    right: 10px;
    bottom: 60px;
    width: 30px;
    height: 30px;
  }
  .goTop .go-top{
    font-size: 30px;
    color: #1ABC9C;
  }
</style>
